//
//  HeicViewController.swift
//  photoTool
//
//  Created by 刘清元 on 2023/1/1.
//

import UIKit
import Photos

class HeicViewController: UIViewController {

    @IBOutlet weak var topImg: UIImageView!
    @IBOutlet weak var topLab: UILabel!
    @IBOutlet weak var heicLab: UILabel!
    @IBOutlet weak var heicImg: UIImageView!
    private var daiZHModel = AlbumModel.init()
    private var yiZHModel = AlbumModel.init()
    private var HEICModel = AlbumModel.init()
    private var canChange = true
    private var listArr:[AlbumModel] = []{
        didSet{
            if listArr.count > 0 {
                makeUI()
            }
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        PhotoSingle.shared.getAllAlbum { list in
            var itemArr:[AlbumModel] = []
            for item in list{
                if ["待转换","已转换","HEIC"].contains(item.albumName){
                    itemArr.append(item)
                }
            }
            self.listArr = itemArr
        }
    }
    func makeUI(){
        for item in self.listArr {
            if item.albumName == "待转换"{
                daiZHModel = item
            }else if item.albumName == "已转换"{
                yiZHModel = item
            }else if item.albumName == "HEIC"{
                HEICModel = item
            }
        }
        beginMission()
    }
    
    func beginMission() {
        // 设置一个定时器
        missionTimer.fire()
    }

    lazy var missionTimer: Timer = {
        let timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerMission), userInfo: nil, repeats: true)
        return timer
    }()
    
    @objc func timerMission() {
        if canChange {
            changeImage(daiZHModel: daiZHModel, yiZHModel: yiZHModel, HEICModel: HEICModel)
        }
    }
    
    func changeImage(daiZHModel:AlbumModel,yiZHModel:AlbumModel,HEICModel:AlbumModel) {
        canChange = false
        let imgArr = PhotoSingle.shared.getImagesFromAlbum(albumModel: daiZHModel, imageCount: 1)
        if imgArr.isEmpty {
            missionTimer.invalidate()
            let alert = UIAlertController.init(title: "提示", message: "转换完成", preferredStyle: .alert)
            let cancelAction = UIAlertAction(title: "确定", style: .cancel)
            alert.addAction(cancelAction)
            self.present(alert, animated: true)
            return
        }
        let model = imgArr.first!
        let assetResult = PHAsset.fetchAssets(withLocalIdentifiers: [model.localIdentifier!], options: nil)
        let options = PHImageRequestOptions.init()
        let asset = assetResult.firstObject!
        PHImageManager.default().requestImageDataAndOrientation(for: asset, options: options) { imageData, dataUTI, orientation, info in
            let image = UIImage.init(data: imageData!)!
            let documentPath = FileTool.init().getDocumentPath()
            let filePath = documentPath+"/image.heic"
            let bottomImage = PhotoSingle.shared.changeJPGToHeic(orignImage: image,filePath: filePath)
            if PhotoSingle.shared.insertImageToAlbum(albumModel: HEICModel, image: bottomImage) {
                // 删除本地图片
                _ = FileTool.init().deleteFileWithPath(path: filePath)
                if PhotoSingle.shared.moveImagesToAlbum(albumModel: yiZHModel, assets: [asset]){
                    if PhotoSingle.shared.deleteImagesFromAlbum(albumModel: daiZHModel, assets: [asset]){
                        DispatchQueue.main.asyncAfter(deadline:.now()+2.0){
                            self.canChange = true
                        }
                    }
                }
            }
        }
    }
}
